<template>
  <div class="">
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item><i class="el-icon-lx-copy"></i> 用户管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <el-input v-model="query.name" placeholder="角色名" class="handle-input mr10"></el-input>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
      </div>

      <el-table :data="roles" border class="table" ref="multipleTable" header-cell-class-name="table-header"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="worker_id" label="ID" width="55" align="center"></el-table-column>
        <el-table-column label="头像" align="center">
          <template #default="scope">
            <el-image class="table-td-thumb" :src="scope.row.worker_photo"
                      :preview-src-list="[scope.row.worker_photo]"></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="worker_name" label="姓名"></el-table-column>
        <el-table-column prop="department" label="部门"></el-table-column>
        <el-table-column prop="worker_post" label="职位"></el-table-column>
        <el-table-column label="操作" width="250" align="center">
          <template #default="scope">
            <el-button type="text" icon="el-icon-search" @click="handleDetail(scope.$index, scope.row)">详情</el-button>
            <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button type="text" icon="el-icon-lx-people" @click="handleAccount(scope.$index, scope.row)">账号
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="handle-row">
<!--        <el-button type="danger" @click="delSelection()">删除选中</el-button>-->
        <el-button type="primary" @click="addRole()">添加角色</el-button>
      </div>

      <!-- 页码 -->
      <div class="pagination">
        <el-pagination background layout="total, prev, pager, next" :current-page="query.pageIndex"
                       :page-size="query.pageSize"
                       :total="query.pageTotal" @current-change="handlePageChange"></el-pagination>
      </div>
    </div>

    <!-- 弹出框 -->
    <el-dialog title="编辑" v-model="model.visible" width="60%">
      <el-form ref="model.form" :model="model.form" label-width="70px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item>
              <div class="demo-image__preview" align="center">
                <div class="crop-demo">
                  <img :src="imgSrc" class="pre-img"/>
                  <div class="crop-demo-btn" v-if="model.isEdit || model.idEdit">
                    选择图片
                    <input class="crop-input" type="file" name="image" accept="image/*" @change="setImage"/>
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-col :span="12">
              <el-form-item label="id">
                <el-input v-model="model.form.worker_id" :disabled='false'></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="用户名">
                <el-input v-model="model.form.worker_name" :disabled="!model.isEdit"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="部门">
                <el-select v-model="model.form.department" placeholder="请选择部门" :disabled="!model.isEdit">
                  <el-option label="客户服务部" value="客户服务部"></el-option>
                  <el-option label="安保部" value="安保部"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="职位">
                <el-select v-model="model.form.worker_post" placeholder="请选择职位" :disabled="!model.isEdit">
                  <el-option label="部长" value="部长"></el-option>
                  <el-option label="员工" value="员工"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="生日">
              <el-form-item prop="date1">
                <el-date-picker type="date" placeholder="选择日期" v-model="model.form.worker_birthday" style="width: 100%;"
                                :disabled="!model.isEdit"></el-date-picker>
              </el-form-item>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性别">
              <el-select v-model="model.form.worker_gender" placeholder="请选择性别" :disabled="!model.isEdit">
                <el-option label="男" value="0"></el-option>
                <el-option label="女" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="电话">
              <el-input v-model="model.form.worker_phone" :disabled="!model.isEdit"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地址">
              <el-input v-model="model.form.worker_address" :disabled="!model.isEdit"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="籍贯">
              <el-input v-model="model.form.worker_native_place" :disabled="!model.isEdit"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input type="textarea" :rows="3" v-model="model.form.remark" :disabled="!model.isEdit"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
				<span class="dialog-footer" v-if="model.isEdit && !model.idEdit">
					<el-button @click="model.visible = false">取 消</el-button>
					<el-button type="primary" @click="saveEdit">保 存</el-button>
				</span>
        <span class="dialog-footer" v-if="!model.isEdit && !model.idEdit">
					<el-button type="primary" @click="model.visible = false">确 定</el-button>
				</span>
        <span class="dialog-footer" v-if="model.idEdit">
					<el-button @click="model.visible = false;model.idEdit=false">取 消</el-button>
					<el-button type="primary" @click="doAddRole">添 加</el-button>
				</span>
      </template>
    </el-dialog>

    <!-- 裁剪框 -->
    <el-dialog title="裁剪图片" v-model="dialogVisible" width="600px">
      <vue-cropper ref="cropper" :src="imgSrc" :ready="cropImage" :zoom="cropImage" :cropmove="cropImage"
                   style="width:100%;height:300px;"></vue-cropper>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="cancelCrop">取 消</el-button>
					<el-button type="primary" @click="doUpload">上 传</el-button>
				</span>
      </template>
    </el-dialog>

    <!--  账号管理弹窗  -->
    <el-dialog
        title="账号管理"
        v-model="accountDialogVisible"
        width="30%">
      <el-form>
        <el-form-item label="用户名">
          <el-input v-model="account.username" :disabled="accountIsEdit"></el-input>
        </el-form-item>
        <el-form-item label="设置新密码">
          <el-input v-model="account.password"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="accountDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveAccount" v-if="accountIsEdit">保存新密码</el-button>
          <el-button type="primary" @click="addAccount" v-if="!accountIsEdit">添加账号</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchData2
}
  from "../api/index";
import WorkerData from "../api/Worker.js"
import VueCropper from "vue-cropperjs";
import "cropperjs/dist/cropper.css";

export default {
  name: 'role',
  data() {
    return {
      query: {
        name: '',
        pageIndex: 1,
        pageSize: 5,
        pageTotal: 0
      },
      roles: [],
      multipleSelection: [],
      model: {
        visible: false,
        idx: 0,
        form: {},
        isEdit: false,
        idEdit: false
      },
      dialogVisible: false,
      fileName: "",
      cropImg: "",
      imgSrc: "", // 裁剪框的图片
      cropImg: "", // 头像框上的图片
      account: {
        username: "",
        password: ""
      },
      accountDialogVisible: false,
      accountIsEdit: true,
      accountWorkId: 0,
    }
  },
  created() {
    this.getData(this.query.pageIndex, this.query.pageSize);
    this.getCount();
  },
  methods: {
    reLoadData() {
      this.getData(this.query.pageIndex, this.query.pageSize, this.query.name);
      this.getCount(this.query.name);
    },
    getData(page, pageSize, word) {
      WorkerData.getList(page, pageSize, word).then(res => {
        console.log(res);
        this.roles = res.data;
      })
    },
    getCount(word) {
      WorkerData.getCount(word).then(res => {
        console.log(res);
        this.query.pageTotal = res.data;
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 删除选中
    delSelection() {
      console.log(this.multipleSelection);
      // let str = this.multipleSelection.reduce((pre, item) => pre + item.worker_id + ',', '');
      // console.log(str.slice(0, -1));
      const requests = [];
      for (let item of this.multipleSelection) {
        let request = this.$axios.request({
          method: 'delete',
          url: '/worker/' + item.worker_id
        })
        requests.push(request);
      }
      this.$axios.all(requests).then(res => {
        console.log(res);
        this.$message("删除成功")
        this.reLoadData();
      })
    },
    // 查看详情按钮
    handleDetail(index, row) {
      this.model.visible = true;
      this.model.form = row;
      this.model.isEdit = false;
      this.imgSrc = this.model.form.worker_photo;
      console.log(this.model.form.worker_photo);
    },
    // 编辑按钮
    handleEdit(index, row) {
      this.model.visible = true;
      this.model.form = row;
      this.model.isEdit = true;
      this.imgSrc = this.model.form.worker_photo;
    },
    // 添加按钮
    addRole() {
      this.model.visible = true;
      this.model.form = {};
      this.model.isEdit = true;
      this.model.idEdit = true;
      this.imgSrc = this.model.form.worker_photo;
    },
    // 保存编辑
    saveEdit() {
      console.log(this.model.form);
      WorkerData.editWorker(this.model.form).then(res => {
        console.log(res);
        if (res.status == 200) {
          this.$message.success("保存成功");
        }
      })
      this.model.visible = false;
    },
    // 保存添加
    doAddRole() {
      console.log(this.model.form);
      WorkerData.addWorker(this.model.form).then(res => {
        console.log(res);
        if (res.status == 200) {
          this.$message.success("添加成功");
        }
        this.reLoadData();
        this.model.visible = false;
      })
    },
    // 分页点击事件
    handlePageChange(val) {
      this.query.pageIndex = val;
      this.getData(this.query.pageIndex, this.query.pageSize, this.query.name);
      this.getCount(this.query.name);
    },
    // 选择图片
    setImage(e) {
      const file = e.target.files[0];
      this.fileName = file.name;
      console.log(this.fileName);
      if (!file.type.includes("image/")) {
        return;
      }
      const reader = new FileReader();
      reader.onload = event => {
        this.dialogVisible = true;
        this.imgSrc = event.target.result;
        this.$refs.cropper &&
        this.$refs.cropper.replace(event.target.result);
      };
      reader.readAsDataURL(file);
    },
    // 裁剪框取消事件
    cancelCrop() {
      this.dialogVisible = false;
      console.log(this.cropImg);
      this.imgSrc = this.model.form.worker_photo;
    },
    // 裁剪框变化事件
    cropImage() {
      this.cropImg = this.$refs.cropper.getCroppedCanvas().toDataURL();
    },
    // 裁剪框上传事件
    doUpload() {
      let _this = this;
      this.$refs.cropper.getCroppedCanvas({
        width: 420,
        height: 213,
        fillColor: '#fff',
        imageSmoothingEnabled: false,
        imageSmoothingQuality: 'high',
      }).toBlob(blob => {
        console.log(blob);
        let formData = new FormData();
        formData.append("file", blob, this.fileName);
        formData.append('name', 'qweqew');
        let config = {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }
        this.$axios.post('/upload', formData, config).then(function (res) {
          if (res.data.code == 1) {
            _this.model.form.worker_photo = res.data.data;
            alert("上传成功");
          } else {
            alert("上传失败");
          }
          _this.dialogVisible = false;
        })
      })
    },
    // 搜索框搜索事件
    handleSearch() {
      this.query.pageIndex = 1;
      this.getData(this.query.pageIndex, this.query.pageSize, this.query.name);
      this.getCount(this.query.name);
    },
    /*打开账户管理*/
    handleAccount(index, row) {
      this.account = {};
      this.accountDialogVisible = true;
      console.log(row)
      this.$axios.get("/account/worker/" + row.worker_id).then(res=>{
        if (res.data.code == 200) {
          this.account.username = res.data.message;
          this.accountIsEdit = true;
        } else {
          this.accountIsEdit = false;
          this.accountWorkId = row.worker_id;
        }
      })
    },
    /*保存账号信息*/
    saveAccount() {
      console.log(this.account);
      if (this.account.password == undefined ||this.account.password === ""){
        this.$message.error("新密码不能为空")
        return;
      }
      this.$axios.put("/account", this.account).then(res=>{
        if(res.data.code == 200) {
          this.$message.success("新密码设置成功");
        } else{
          this.$message.error("设置失败，请稍后重试")
        }
        this.accountDialogVisible = false;
      })
    },
    /*添加账号信息*/
    addAccount(){
      console.log(this.account);
      if (this.account.username == undefined ||this.account.username === "" || this.account.password == undefined ||this.account.password === "") {
        this.$message.error("账号和密码不能为空")
        return;
      }
      this.$axios.post("account", {
        id: this.accountWorkId,
        type: 0,
        account: this.account
      }).then(res=>{
        if (res.data.code == 200) {
          this.$message.success("账户添加成功");
        }else{
          this.$message.error("设置失败，请稍后重试")
        }
        this.accountDialogVisible = false;
      })
    }
  },
  components: {
    VueCropper
  }
}
</script>

<style>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.handle-row {
  margin-top: 20px;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}

.content-title {
  font-weight: 400;
  line-height: 50px;
  margin: 10px 0;
  font-size: 22px;
  color: #1f2f3d;
}

.pre-img {
  width: 100px;
  height: 100px;
  background: #f8f8f8;
  border: 1px solid #eee;
  border-radius: 5px;
}

.crop-demo {
  display: flex;
  align-items: flex-end;
}

.crop-demo-btn {
  position: relative;
  width: 100px;
  height: 40px;
  line-height: 40px;
  padding: 0 20px;
  margin-left: 30px;
  background-color: #409eff;
  color: #fff;
  font-size: 14px;
  border-radius: 4px;
  box-sizing: border-box;
}

.crop-input {
  position: absolute;
  width: 100px;
  height: 40px;
  left: 0;
  top: 0;
  opacity: 0;
  cursor: pointer;
}
</style>
